package com.dff.jrfw;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.dff.jrfw.databinding.ActivityForgotPsdThreeBinding;
import com.dff.jrfw.dialog.ResetLoginPsdSuccessDialog;
import com.dff.jrfw.model.PasswordStrategyModel;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtils;
import com.dff.jrfw.requestBody.PasswordResetDto;
import com.dff.jrfw.requestBody.QueryUserPSApiDto;
import com.dff.jrfw.utils.GsonUtils;
import com.dff.jrfw.utils.ToastUtil;
import com.dff.jrfw.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.MessageFormat;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class ForgotPsdThreeActivity extends BaseActivity implements View.OnClickListener {

    private ActivityForgotPsdThreeBinding binding;
    private int psdVisible = 0;    //默认密码不可见
    private String mobile;
    private String code;
    private String username;

    public static void callMe(Context context, String mobile, String code, String username) {
        Intent intent = new Intent(context, ForgotPsdThreeActivity.class);
        intent.putExtra("mobile", mobile);
        intent.putExtra("code", code);
        intent.putExtra("username", username);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_forgot_psd_three);
        mobile = getIntent().getStringExtra("mobile");
        code = getIntent().getStringExtra("code");
        username = getIntent().getStringExtra("username");
        initView();
    }

    private void initView() {
        getPsdStrategy();
        binding.ivBack.setOnClickListener(this);
        binding.btnSure.setOnClickListener(this);
        binding.ivEye.setOnClickListener(this);
        binding.ivInputClearPsd.setOnClickListener(this);
        binding.ivInputClearPsdAgain.setOnClickListener(this);
        binding.etNewPsd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocus) {
                if (isFocus) {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    binding.viewEtNewPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                }
            }
        });
        binding.etNewPsdAgain.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocus) {
                if (isFocus) {
                    binding.tvErrorAgain.setVisibility(View.INVISIBLE);
                    binding.viewEtNewPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                }
            }
        });
        binding.etNewPsd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etNewPsd = charSequence.toString().trim();
                if (etNewPsd.length() == 0) {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    binding.viewEtNewPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                    binding.ivInputClearPsd.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClearPsd.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.etNewPsdAgain.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etNewPsdAgain = charSequence.toString().trim();
                if (etNewPsdAgain.length() == 0) {
                    binding.tvErrorAgain.setVisibility(View.INVISIBLE);
                    binding.viewEtNewPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                    binding.ivInputClearPsdAgain.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClearPsdAgain.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_sure:
                passwordReset();
                Util.hideKeyBoard(binding.btnSure);
                break;
            case R.id.iv_eye:
                if (psdVisible == 0) {
                    psdVisible = 1;
                    binding.ivEye.setImageResource(R.drawable.open_eye);
                    binding.etNewPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    binding.etNewPsdAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    psdVisible = 0;
                    binding.ivEye.setImageResource(R.drawable.cl_eye);
                    binding.etNewPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    binding.etNewPsdAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.iv_input_clear_psd:
                binding.etNewPsd.setText("");
                break;
            case R.id.iv_input_clear_psd_again:
                binding.etNewPsdAgain.setText("");
                break;
        }
    }


    private void passwordReset() {
        String etNewPsd = binding.etNewPsd.getText().toString().trim();
        String etNewPsdAgain = binding.etNewPsdAgain.getText().toString().trim();
        binding.viewEtNewPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
        binding.viewEtNewPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
        binding.tvError.setVisibility(View.GONE);
        if (TextUtils.isEmpty(etNewPsd)) {
            binding.tvError.setVisibility(View.VISIBLE);
            binding.tvError.setText("请登录输入密码");
            binding.viewEtNewPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
            return;
        }
        if (TextUtils.isEmpty(etNewPsdAgain)) {
            binding.tvError.setVisibility(View.VISIBLE);
            binding.tvError.setText("请确认登录密码");
            binding.viewEtNewPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
            return;
        }

//        if (!InputStrCheckUtil.isRightLoginPsd(etNewPsd)) {
//            binding.tvError.setVisibility(View.VISIBLE);
//            binding.viewEtNewPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
//            return;
//        }

        if (!etNewPsd.equals(etNewPsdAgain)) {
            binding.tvErrorAgain.setVisibility(View.VISIBLE);
            binding.viewEtNewPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
            binding.viewEtNewPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
            return;
        }


        PasswordResetDto passwordResetDto = new PasswordResetDto();
        passwordResetDto.setResetType("mobile");
        passwordResetDto.setMobile(mobile);
        passwordResetDto.setCaptcha(code);
        passwordResetDto.setNewPassword(etNewPsd);
        passwordResetDto.setUsername(username);
        RetrofitUtils.getService().passwordReset("1", "1", passwordResetDto).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            ResetLoginPsdSuccessDialog resetLoginPsdSuccessDialog = new ResetLoginPsdSuccessDialog(ForgotPsdThreeActivity.this);
                            resetLoginPsdSuccessDialog.setOnDismissListener(v -> LoginActivity.callMe(ForgotPsdThreeActivity.this, username));
                            resetLoginPsdSuccessDialog.show();
//                        } else if (code == 904) {
//                            ToastUtil.toast("新旧密码不能相同");
//                        } else if (code == 906) {
//                            ToastUtil.toast("验证码错误");
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void getPsdStrategy() {
        QueryUserPSApiDto queryUserPSApiDto = new QueryUserPSApiDto();
        queryUserPSApiDto.setUserNo(username);
        RetrofitUtils.getService().getPsdStrategy("1", "1", queryUserPSApiDto).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            String data = jsonObject.getString("data");
                            PasswordStrategyModel passwordStrategyModel = GsonUtils.gsonToBean(data, PasswordStrategyModel.class);
                            if (passwordStrategyModel != null) {
                                String strength;
                                switch (passwordStrategyModel.getPasswordStrength()) {
                                    case "2":
                                        strength = ",必需包含数字和字母";
                                        break;
                                    case "3":
                                        strength = ",必需包含数字、大写字母和小写字母";
                                        break;
                                    default:
                                        strength = "";
                                }
                                binding.tvForgotPsd.setText(MessageFormat.format("请输入{0}~{1}位密码{2}", passwordStrategyModel.getMinLength(), passwordStrategyModel.getMaxLength(), strength));
                            }
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}